from helpers import updateInfo
import pickle
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Advertiser class """
    def get(self):
        
        user = users.get_current_user()
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
            
        current_user=updateInfo.getCurrentUser(user)
    
        purchaseTable=0
    
        if (current_user.realMoney==0):
            purchaseTable=1
        else:
            purchaseTable=0
        
        q_1 = db.GqlQuery("SELECT * FROM Competition WHERE owner = :1 AND isAd= :2" , user,True)
        q_1=q_1.fetch(1000)
        HaveArenaOrNot = len(q_1)
        
        competition_table_Text="\ndata.addRows(%d);\n" % (len(q_1))
        comp_title = ""
        i=0
        for competition in q_1:
            membersCount=len(competition.members)
            competition.title=competition.title.replace("'","\\'")
            comp_title = competition.title
            competition_table_Text+="data.setCell(%d, 0, '%s', '<a href=\"/advertise?id=%s\">%s</a>',{style: 'font-weight:bold;'});\n" % (i,comp_title,competition.key(),comp_title)
            competition_table_Text+="data.setCell(%d, 1, %d,'%d',{style: 'text-align:center;'});\n" % (i,membersCount,membersCount)
            competition_table_Text+="data.setCell(%d, 2, %d, '$%d',{style: 'text-align:center;'});\n" % (i,competition.advamount,competition.advamount)
            competition_table_Text+="data.setCell(%d, 3, '%s','%s',{style: 'text-align:center;'});\n" % (i,competition.startdate,competition.startdate)
            competition_table_Text+="data.setCell(%d, 4, '%s','%s',{style: 'text-align:center;'});\n" % (i,competition.enddate,competition.enddate)
            i=i+1
        
        bool = 0
        comp_key = self.request.get('id',0)
        competition_graph_Chart=""
    
        if (comp_key!=0): 
            try:
                competition=db.get(db.Key(comp_key))
            except:
                self.response.out.write("Wrong ID provided")
                return
            comp_title=competition.title
            bool = 1
            keywordsList=pickle.loads(competition.arenaKeywords)
            competition_graph_Chart="\ndata2.addRows(%d);\n" % (len(competition.compKeywordsAmount))
            
            # b is list which in every cell has the number of people who chosen it
            b = [0]*(len(competition.compKeywordsAmount))
            for item in competition.membersChoice:
                b[item] = b[item] + 1
            i = 0    
            for keyword in keywordsList:    
                OneOptionStocks =""
                for word in keyword:
                    current_word = db.get(word).stockname
                    OneOptionStocks+= current_word + ","
                if len(OneOptionStocks)>0:
                    OneOptionStocks=OneOptionStocks[0:len(OneOptionStocks)-1]
                competition_graph_Chart+="data2.setCell(%d, 0, '%s');\n" % (i,OneOptionStocks)
                competition_graph_Chart+="data2.setCell(%d, 1, %d);\n" % (i,b[i])
                i=i+1
        
        template_values = {
            'categoryName' : "Advertiser Page %s" % updateInfo.createToolTip("advertise"),
            'bool' : bool,
            'HaveArenaOrNot' : HaveArenaOrNot,
            'comp_title' : comp_title,
            'competition_table_Text':competition_table_Text,
            'competition_graph_Chart':competition_graph_Chart,
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'setHead' : 1,
            'purchaseTable' : purchaseTable,
            'realMoneyAmount': current_user.realMoney,
            'maincontent' : 'account_main.html',
            'headContent' : 'advertiser_head.html',
            'account_main_content' : 'advertiser_main.html',
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))

    def post(self):
        user = users.get_current_user()
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        q_1 = db.GqlQuery("SELECT * FROM TrendUsers WHERE tuser=:1",user)
        q_1=q_1.fetch(1)
        try:
            purchaseAmount=float(self.request.get('investAmount'))
        except:
            self.redirect('/report?msg=13')
            return
        q_1[0].realMoney+=float(purchaseAmount)
        q_1[0].put()
        self.redirect('/advertise')

application = webapp.WSGIApplication(
                                     [('/advertise', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
